package root.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author 吕梁山
 * @date 2018/10/23
 */
public class DateUtils {

    public static final SimpleDateFormat FORMAT_YDMHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static final SimpleDateFormat FORMAT_YDM = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 获取N天后的日期
     */
    public static String getBeforeNDayDate(int days) {
        String date = FORMAT_YDM.format(new Date());
        return getBeforeDateNDayDate(date, days);
    }

    /**
     * 获取某个日期N天前的日期
     */
    public static String getBeforeDateNDayDate(String date, int days) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(FORMAT_YDM.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - days);
        Date time = calendar.getTime();
        return FORMAT_YDM.format(time);
    }

    /**
     * 当根据日期进行分页时获取开始日期
     */
    public static String getStartDateByPageNumber(int pageNumber, int pageSize) throws ParseException {
        String startDate = FORMAT_YDM.format(new Date());
        for (int i = 0; i < pageNumber; i++) {
            startDate = getBeforeDateNDayDate(startDate, i == 0 ? pageSize - 1 : pageSize);
        }
        return startDate;
    }

    /**
     * 当根据日期进行分页时获取结束日期
     */
    public static String getEndDateByPageNumber(int pageNumber, int pageSize) throws ParseException {
        String endDate = FORMAT_YDM.format(new Date());
        for (int i = 0; i < pageNumber - 1; i++) {
            endDate = getBeforeDateNDayDate(endDate, pageSize);
        }
        return endDate;
    }
}
